package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.*;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.pojo.MerchantVegetablePlot;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantPlotRegionService;
import com.wmh.baseservice.merchant.service.MerchantVegetablePlotService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author wmh generator
 * @since 2021-12-24
 */
@Api(tags = "商家端-土地管理相关接口")
@RestController
@RequestMapping(value = "merchant/merchantVegetablePlot", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
@RequiresPermissions(logical = Logical.OR, value = {"土地管理操作", "所有权限"})
public class MerchantVegetablePlotController {

    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantInfoService merchantInfoService;

    @ApiOperation("土地详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String detail(Long id) {
        MerchantVegetablePlot merchantVegetablePlot;
        Long merchantId = (Long) request.getAttribute("id");
        if (CommUtil.checkNull(merchantId)) {
            merchantVegetablePlot = merchantVegetablePlotService.getOne(
                    new QueryWrapper<MerchantVegetablePlot>().eq(MerchantVegetablePlot.RAW_MERCHANT_ID, merchantId));
        } else {
            merchantVegetablePlot = merchantVegetablePlotService.getByIdForUpdate(id);
        }

        return ReturnBody.success(merchantVegetablePlot);
    }

    @ApiOperation("图片上传")
    @PostMapping("uploadImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String uploadImg(MultipartFile[] file, Long urlId) {
        JSONObject object = new JSONObject();
        Long timeId = 0L;
        //生成随机id文件夹
        if (CommUtil.checkNull(urlId)) {
            timeId = urlId;
        } else {
            timeId = UUIDUtil.getTimeId();
        }
        List<String> uploads = FileUtil.uploads("plot/" + timeId, file, "file");
        if (!CommUtil.checkNull(uploads)) {
            return ReturnBody.error("图片上传错误");
        }
        //返回随机id，前端添加商品时传给数据库存储该文件夹字段，方便后面删除商品的时候把图片一起删除
        object.put("uploads", uploads);
        object.put("id", timeId);
        return ReturnBody.success(object);
    }

    @ApiOperation("完善土地信息")
    @PostMapping("savePlot")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"avatar", "plotName", "name", "phone", "businessType", "openType", "address", "content"})
    public String savePlot(Long id, String avatar, String banner, String plotName, String name, String phone, Double wide, Double lon, Double mu, Integer businessType,
                           Integer openType, String pickOpenTime, String pickOverTime, String growOpenTime, String growOverTime, String lat, String lng,
                           String address, String overview, String content, Long urlId, Integer growCount, String label, BigDecimal deposit, String app) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            merchantId = parentMerchantInfo.getId();
        }
        MerchantVegetablePlot plot = merchantVegetablePlotService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(plot)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (!plot.getRawMerchantId().equals(merchantId)) {
            return ReturnBody.error("只有土地原商家可修改信息");
        }
        //时间校验
        if (businessType == 0) {
            if (!CommUtil.checkNull(pickOpenTime, pickOverTime)) {
                return ReturnBody.error("请选择采摘开放和关闭时间");
            }
        } else if (businessType == 1) {
            plot.setGrowCount(CommUtil.checkNull(growCount) ? growCount : -1);
            if (!CommUtil.checkNull(growOpenTime, growOverTime)) {
                return ReturnBody.error("请选择种植开放和关闭时间");
            }
        } else {
            plot.setGrowCount(CommUtil.checkNull(growCount) ? growCount : -1);
            if (!CommUtil.checkNull(growOpenTime, growOverTime, pickOpenTime, pickOverTime)) {
                return ReturnBody.error("请完整选择采摘和种植的开放关闭时间");
            }
        }


        //路径id没传则生成
        if (CommUtil.checkNull(plot.getUrlId())) {
            urlId = plot.getUrlId();
        } else {
            urlId = UUIDUtil.getTimeId();
        }


        //比较html
        if (CommUtil.checkNull(plot.getContent())) {
            List<String> imgElementList = FileUtil.getImgElementList(plot.getContent(), content);
            if (imgElementList.size() != 0) {
                imgElementList.forEach(item -> FileUtil.delete(item));
            }
        }
        if (CommUtil.checkNull(content) && CommUtil.checkNull(app)) {
            Document dom = Jsoup.parse(content);
            Elements imgTag = dom.select("img");
            imgTag.forEach(item -> item.attr("style", "max-width:100%"));
            content = dom.body().toString().replace("<body>\n", "").replace("\n</body>", "");
        }
        plot.setContent(content);
        //删除之前的主图或背景图
        if (CommUtil.checkNull(avatar)) {
            if (avatar.contains("base64")) {
                if (CommUtil.checkNull(plot.getAvatar()) && !plot.getAvatar().contains("default")) {
                    FileUtil.delete(plot.getAvatar());
                }
                String url = Base64Util.generateImage("plot/" + urlId, avatar);
                if (!CommUtil.checkNull(url)) {
                    return ReturnBody.error("图片上传错误");
                }
                plot.setAvatar(url);
            }
        }
        if (CommUtil.checkNull(banner)) {
            if (banner.contains("base64")) {
                if (CommUtil.checkNull(plot.getBanner()) && !plot.getBanner().contains("plotBanner")) {
                    FileUtil.delete(plot.getBanner());
                }
                String url = Base64Util.generateImage("plot/" + urlId, banner);
                if (!CommUtil.checkNull(url)) {
                    return ReturnBody.error("图片上传错误");
                }
                plot.setBanner(url);
            }
        }

        //生成土地分享二维码(扫码进入果蔬列表页面)
        try {
            if (!CommUtil.checkNull(plot.getShareBanner())) {
                String qrCodeUrl = QrCodeUtil.getQrCodeSave("id=" + plot.getId() + "&type=0", "plot", "pageA/growVegetables/vegetablesList");
                plot.setShareBanner(qrCodeUrl.replace("/www/server/project/", ""));
            }
        } catch (WxErrorException | IOException e) {
            LogUtil.error("生成土地分享二维码错误，土地id{}", plot.getId());
            throw new ServiceException("生成土地分享二维码错误");
        }


        //赋值剩余的参数
        plot.setUrlId(urlId).setAddress(address).setPlotName(plotName).setName(name).setPhone(phone).setLat(lat).setLng(lng).setBusinessType(businessType).
                setBusinessType(businessType).setOpenType(openType).setPickOpenTime(pickOpenTime).setPickOverTime(pickOverTime).setGrowOpenTime(growOpenTime).
                setGrowOverTime(growOverTime).setGrowCount(growCount).setWide(wide).setLon(lon).setMu(mu).setOverview(overview).setContent(content).setLabel(label).
                setDeposit(deposit).setStatus(plot.getStatus() == 0 ? 1 : plot.getStatus());
        if (!merchantVegetablePlotService.updateById(plot)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }

        return ReturnBody.success();
    }
}
